/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cageballcommon.io.impl;

import cageballcommon.exceptions.CageballIOException;
import cageballcommon.exceptions.CageballParseException;
import cageballcommon.io.interfaces.CageballReader;
import cageballcommon.messages.Action;
import cageballcommon.messages.InitTeam;
import cageballcommon.messages.State;
import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

/**
 *
 * @author kanonas
 */
public class CageballFileReader implements CageballReader {

    private BufferedReader in;
    private Gson gson;

    public CageballFileReader(File file) throws FileNotFoundException {
        in = new BufferedReader(new FileReader(file));
        gson = new Gson();
    }

    public State readState() throws CageballIOException, CageballParseException {
        try {
            return gson.fromJson(readLine(), State.class);
        } catch (JsonParseException ex) {
            throw new CageballParseException(ex.getMessage());
        }
    }

    public Action readAction() throws CageballIOException, CageballParseException {
        try {
            return gson.fromJson(readLine(), Action.class);
        } catch (JsonParseException ex) {
            throw new CageballParseException(ex.getMessage());
        }
    }

    public InitTeam readInitTeam() throws CageballIOException, CageballParseException {
        try {
            return gson.fromJson(readLine(), InitTeam.class);
        } catch (JsonParseException ex) {
            throw new CageballParseException(ex.getMessage());
        }
    }

    public Properties readProperties() throws CageballIOException, CageballParseException {
        try {
            return gson.fromJson(readLine(), Properties.class);
        } catch (JsonParseException ex) {
            throw new CageballParseException(ex.getMessage());
        }
    }

    public void close() throws CageballIOException {
        try {
            in.close();
        } catch (IOException ex) {
            throw new CageballIOException(ex.getMessage());
        }
    }

    private String readLine() throws CageballIOException {
        try {
            String line = in.readLine();
            if (line == null) {
                throw new CageballIOException("Error reading");
            }
            return line;
        } catch (IOException ex) {
            throw new CageballIOException(ex.getMessage());
        }
    }
}
